package com.forevershine.business.persistent;

import java.io.IOException;
import java.util.Properties;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.google.inject.Inject;
import com.google.inject.name.Named;

public class MySqlAccessor implements IDataAccessor {

	@Inject
	@Named(value = "mysql.config.file")
	private String mysqlConfigResource;

	private String jdbcConfig = "jdbc.properties";

	private static SqlSessionFactory sqlMapper;

	@Inject
	private void init() {

		try {
			Properties prop = new Properties();
			prop.load(MySqlAccessor.class.getClassLoader().getResourceAsStream(jdbcConfig));
			sqlMapper = new SqlSessionFactoryBuilder().build(Resources
					.getResourceAsReader(mysqlConfigResource), prop);

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public synchronized SqlSession getSession() {
		if (sqlMapper != null) {
			return sqlMapper.openSession();
		} else {
			init();
			return sqlMapper.openSession();
		}
	}

}
